package io.terminus.paas.profiler

import com.alibaba.dubbo.common.Constants
import com.alibaba.dubbo.common.URL
import com.alibaba.dubbo.registry.RegistryService
import io.terminus.paas.profiler.registry.RegistryServiceRouter
import org.springframework.beans.factory.annotation.Autowired

/**
 * Created by gengrong on 16/3/16.
 *
 * 提供Dubbo服务治理可用对象,直接操作注册中心
 * 服务治理的业务服务继承于此
 */
open class AbstractProfilerService {

    @Autowired
    private lateinit var registryServiceRouter: RegistryServiceRouter

    val empty_map = mapOf<String, Map<Long, URL>>();

    fun getRegistryService(registryAddress: String): RegistryService {
        return registryServiceRouter.getInstance(registryAddress)
    }

    // TODO 多源访问,具有严重的性能问题
    fun getRegistryCache(registryAddress: String): Map<String, Map<String, Map<Long, URL>>> {
        return registryServiceRouter.getRegistryServerSync(registryAddress).registryCache
    }

    fun getUrls(registryAddress: String, type: String): Map<String, Map<Long, URL>> {
        val ret = getRegistryCache(registryAddress).get(type)
        ret ?: return empty_map
        return ret;
    }

    fun getProviderUrls(registryAddress: String): Map<String, Map<Long, URL>> {
        return getUrls(registryAddress, Constants.PROVIDERS_CATEGORY);
    }

    fun getRouteUrls(registryAddress: String): Map<String, Map<Long, URL>> {
        return getUrls(registryAddress, Constants.ROUTERS_CATEGORY);
    }

    fun getConsumerUrls(registryAddress: String): Map<String, Map<Long, URL>> {
        return getUrls(registryAddress, Constants.CONSUMERS_CATEGORY);
    }

    fun getConfiguratorUrls(registryAddress: String): Map<String, Map<Long, URL>> {
        return getUrls(registryAddress, Constants.CONFIGURATORS_CATEGORY);
    }

}